<template>
  <div class="handle-data-container">
    <el-dialog v-model="dialog" :title="dialogTitle" top="50px" :before-close="cancelForm" :close-on-click-modal="false">
      <div class="demo-drawer__content">
        <el-form class="handle-form-container" :model="form" ref="handleForm" v-if="HandlerItemData && HandlerItemData.length">
          <div v-for="handlerItem in HandlerItemData" :key="handlerItem.key">
            <el-form-item v-if="!inputShowAdd(handlerItem.key)" :key="handlerItem.key" :label="handlerItem.label" :label-width="120" :prop="handlerItem.key">
              <el-input v-if="handlerItem.category === 'input'" v-model="form[handlerItem.key]" :type="handlerItem.type"
                :disabled="handlerItem.updateDisabled && updateDisabled">
                <template v-if="handlerItem.key === 'bidfloor' || handlerItem.key === 'budget'" #append>元</template>
              </el-input>
              <div v-else-if="handlerItem.category === 'select'">
                <el-select v-model="form[handlerItem.key]"
                  :placeholder="'请选择'"
                  :disabled="(handlerItem.key === 'status' && props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) || (handlerItem.key === 'pkgtype' && props.handleType === HANDLE_TYPE_ENUM.TYPE_UPDATE)">
                  <el-option v-for="optionItem in handlerItem.options" :key="optionItem.value" :label="optionItem.label"
                    :value="optionItem.value" />
                </el-select>
                <span v-if="handlerItem.key === 'btime' || handlerItem.key === 'etime'" style="margin-left: 10px;">H</span>
              </div>
              <TagInput v-else-if="handlerItem.category === 'tag-input'" @onTagInputComplete="onTagInputComplete" :tagData="form[handlerItem.key]"/>
            </el-form-item>
          </div>
        </el-form>
        <div class="footer-container">
          <el-button @click="cancelForm">取消</el-button>
          <el-button type="primary" @click="onClick">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
  
<script setup lang='ts'>
/**
 * 新增的时候 pkg 和 md5需要格外注意，后端有校验
 * 
 http://tf.jinshanju.com/manage/add?
 name=helloworld&pkg=com.ss.android.ugc.aweme.lite&md5=b8af36e762cf98511054e2c678dc2018
 &url=12123&vnm=12.1.1&vcd=120101&cpuModel=&keywords=&bidfloor=1200
 &budget=1200&downloadnum=12&channel=hemu_dsp&mlink=&tagid=&size=12
 * 
 */
import { reactive, ref, watch, defineProps, computed } from 'vue';
import { HandlerItemData as OriginHandlerItemData, HANDLE_TYPE_ENUM } from '../../../types/home/constData';
import type { IHandlerItemData, IListItemData } from '../../../types/home/type'
import { multiplicationHundred, divisionHundred, isNumber } from '@/utils/index'
import { reqManagelistAddV2, reqManagelistUpdateV2, reqManagelistItemV2 } from '@/api/home/index.ts'
import TagInput from './tag-input/TagInput.vue'

const emit = defineEmits(['onHandlerCompleted'])
const props = defineProps<{
  originData: any,
  handleType: string,
  showFormKey: string[] | null
}>()
const handleForm = ref()
const dialogTitle = ref<string>('新增')
const dialog = ref<boolean>(false)
const updateDisabled = ref<boolean>(false)
const formNoneVal: IListItemData = {
  name: '',
  pkg: '',
  md5: '',
  url: '',
  vnm: '',
  vcd: '',
  cpuModel: '',
  pkgtype: 0,
  keywords: '',
  bidfloor: null,
  budget: null,
  downloadnum: null,
  btime: null,
  etime: null,
  channel: '',
  mlink: '',
  tagid: '',
  size: '',
  rtaurl: '',
  customer: '',
  detailList: []
}

let form = reactive<IListItemData>(formNoneVal)
const updateOriginStatus = ref<number | null>(null)
// 动态获取要展示的formkey
let HandlerItemData = ref<IHandlerItemData[]>([])
const initFormShowKey = () => {
  const indexFormListShowKey: string[] = props.showFormKey || []
  const keyArr: IHandlerItemData[] = []
  OriginHandlerItemData.forEach((item: IHandlerItemData) => {
    if (indexFormListShowKey.some((key: string) => key === item.key)) {
      keyArr.push({...item})
    }
  })
  return keyArr
}


// 新增的时候 appid 和 status 不展示
const inputShowAdd = computed(()=> (key: string) => {
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
    return key === 'appid' || key === 'status'
  }
  return false
})
const cancelForm = () => {
  handleForm.value && handleForm.value.resetFields()
  form = reactive<IListItemData>(formNoneVal)
  updateDisabled.value = false
  handleDialog(false)
}
const onClick = () => {
  const isValiate = valiateForm()
  if (!isValiate) return
  onSubmit()
}

const onSubmit = () => {
  let requestFunc: Function | null = null
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
    requestFunc = reqManagelistAddV2
  } else {
    requestFunc = reqManagelistUpdateV2
  }
  const targetForm = {
    ...form,
    id: form.appid,
    cpumodel: form.cpuModel,
  }
  if (targetForm.bidfloor != null && targetForm.bidfloor != undefined) {
    targetForm.bidfloor = multiplicationHundred(Number(targetForm.bidfloor))
  }
  if (targetForm.budget != null && targetForm.budget != undefined) {
    targetForm.budget = multiplicationHundred(Number(targetForm.budget))
  }
  if (targetForm.detailList && targetForm.detailList.length) {
    targetForm.detailList = targetForm.detailList.map((item) => {
      return {
        ...item,
        bidfloor: multiplicationHundred(Number(item.bidfloor))
      }
    })
  }
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
    targetForm.status && delete targetForm.status
    targetForm.appid && delete targetForm.appid
    targetForm.id && delete targetForm.id
  } else {
  }
  if (!isNumber(targetForm.btime as string)|| !isNumber(targetForm.etime as string)) {
    targetForm.btime = null;
    targetForm.etime = null;
  } else if (targetForm.btime !== null && targetForm.etime !== null && Number(targetForm.btime) > Number(targetForm.etime)) {
    ElMessage({
      type: 'warning',
      message: '结束时间必须大于开始时间'
    })
    return;
  }
  if (requestFunc === null) return
  requestFunc(targetForm).then((res: any) => {
    const { code, data, msg } = res
    if (code === 0) {
      console.log(data)
      ElMessage({
        type: 'success',
        message: `${dialogTitle.value}成功`
      })
      emit('onHandlerCompleted')
      cancelForm()
    } else {
      ElMessage({
        type: 'warning',
        message: msg
      })
    }
  })
}


const valiateForm = () => {
  for (let index = 0; index < HandlerItemData.value.length; index++) {
    const item: IHandlerItemData = HandlerItemData.value[index]
    const keyVal = form[item.key as string]
    const keyMapVal: any = item.key !== 'detailList' ? `${keyVal}` : (keyVal || []).length
    if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
      if (!!item.require && !keyMapVal) {
        const message = `${item.label}为必填项`
        ElMessage({
          type: 'warning',
          message
        })
        return false
      }
    } else {
      if (!!item.require && !item.updateDisabled && !keyMapVal) {
        const message = `${item.label}为必填项`
        ElMessage({
          type: 'warning',
          message
        })
        return false
      }
    }
    // 如果detailList有值，需要检验一下是否所有的数据都填写完整
    if (item.key === 'detailList') {
      const isNotAllComplete: boolean = keyVal.some((item: any) => !item.bidfloor || !item.keyword || !item.tagid)
      if (isNotAllComplete) {
        ElMessage({
          type: 'warning',
          message: '请完整填写广告位列表'
        })
        return !isNotAllComplete
      }
    }
  }
  // 更新时，任何状态都可以改成下架=-3，但只有-3可以改成上架=0
  if (props.handleType === HANDLE_TYPE_ENUM.TYPE_UPDATE && form.status === 0 && updateOriginStatus.value !== -3) {
    ElMessage({
      type: 'warning',
      message: '只有下架状态才能修改为上架'
    })
    return false
  }
  return true
}
watch(dialog, (newVal) => {
  setTimeout(() => {
    if (!!newVal) {
      if (props.handleType === HANDLE_TYPE_ENUM.TYPE_ADD) {
        dialogTitle.value = '新增'
      } else {
        dialogTitle.value = '更新'
        getManagelistItem(props.originData.appid)
      }
    }
    HandlerItemData.value = initFormShowKey()
  }, 0)
})
const resetFormValue = (data: any) => {
  form = Object.assign(form, data)
  // 更新时，任何状态都可以改成下架=-3，但只有-3可以改成上架=0
  updateOriginStatus.value = form.status!
  updateDisabled.value = true
}
const getManagelistItem = (appid: string | undefined) => {
  reqManagelistItemV2({ appid }).then((res: any) => {
    const { code, data, msg } = res
    if (code === 0) {
      if (data.bidfloor != null && data.bidfloor != undefined) {
        data.bidfloor = divisionHundred(Number(data.bidfloor))
      }
      if (data.budget != null && data.budget != undefined) {
        data.budget = divisionHundred(Number(data.budget))
      }
      if (data.detailList && data.detailList.length) {
        data.detailList.forEach((item: any) => {
          item.bidfloor = divisionHundred(Number(item.bidfloor))
        })
      }
      if (data.pkgtype === null) {
        data.pkgtype = 0
      }
      resetFormValue(data)
    } else {
      ElMessage({
        type: 'warning',
        message: msg
      })
    }
  })
}
const handleDialog = (val: boolean) => {
  dialog.value = val
}

const onTagInputComplete = (type: string, data: any, index: number) => {
  if (!form.detailList) form.detailList = []
  if (type === HANDLE_TYPE_ENUM.TYPE_ADD) {
    form.detailList.push(data)
  } else if(type === HANDLE_TYPE_ENUM.TYPE_UPDATE) {
    form.detailList.splice(index, 1, data)
  } else if(type === HANDLE_TYPE_ENUM.TYPE_DELETE) {
    form.detailList.splice(index, 1)
  } 
}

defineExpose({
  handleDialog
})
</script>
  
<style scope lang="scss">
.demo-drawer__content{
  .handle-form-container{
    height: 700px;
    overflow: auto;
    padding-right: 15px;
  }
}
.footer-container {
  margin-top: 30px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>